from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from books.models import BooksModel
from books.ser import BooksSer
from cart.models import CartModel
from cart.ser import CartSer


# Create your views here.
#借阅列表
class CartList(APIView):
    # authentication_classes = [MyAuthentication]
    def get(self,request):
        userid=request.query_params.get('userid')
        cart=CartModel.objects.filter(userid=userid)
        print(cart)
        ser=CartSer(cart,many=True)
        return Response({"msg":"ok","data":ser.data})

#添加借阅
class CartAdd(APIView):
    def post(self,request):
        cart=CartModel.objects.filter(bookid=request.data.get('bookid'),userid=request.data.get('userid')).first()
        if cart:
            cart.count+=1
            cart.save()
            return Response({"msg":"再次借阅成功","code":200})
        else:
            ser=CartSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({"msg":"借阅成功成功","code":200})
            else:
                return Response(ser.errors)

#删除借阅数据
class DeleteShopping(APIView):
    def delete(self,request):
        id = request.query_params.get('id')
        CartModel.objects.filter(id=id).delete()
        return Response({"msg": "删除成功！！！", "code": 200})

#删除多条数据
class DeleteShoppings(APIView):
    def post(self,request):
        ids=request.data.get('ids')
        CartModel.objects.filter(id__in=ids).delete()
        return Response({"msg": "删除成功！！！", "code": 200})

